<?php
class lesson extends parent_class
{
	public $id=0;
	public $title="";
	public $date="";
	public $articles="";
	
	public function __construct($id=0)
	{
		if ($id>0)
		{
			return $this->get_byid($id);
		}
	}
	
	public function get_byid($id=0)
	{
		if ($id<1)
		{
			if ($this->id>0)
			{
				$id=$this->id;
			}
			else
			{
				return false;
			}
		}
		$id=intval($id);
		
		$query="SELECT * FROM `lessons` WHERE `id`='".$id."'";
		if ($result=db::$db->query($query))
		{
			if($result->num_rows==1)
			{
				$row=$result->fetch_object();
				$this->id=$row->id;
				$this->title=$row->title;
				$this->date=$row->date;
				$this->articles=$row->articles;
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			$this->error(2);
		}
	}
	
	public function add()
	{
		$query="INSERT INTO `lessons` VALUES 
				(NULL,'$this->title','$this->date','$this->articles')";
		if (db::$db->query($query))
		{
			return true;
		}
		else
		{
			$this->error(2);
		}
	}
	
	public function remove($id=0)
	{
		if ($id<1)
		{
			if ($this->id>0)
			{
				$id=$this->id;
			}
			else
			{
				return false;
			}
		}
		if (!($this->exist()))
		{
			return false;
		}
		
		$query="DELETE FROM `lessons` WHERE `id`='".intval($id)."'LIMIT 1";
		
		if (db::$db->query($query))
		{
			return true;
		}
		else
		{
			$this->error(2);
		}
	}
	
	public function update($id=0)
	{
	if ($id<1)
		{
			if ($this->id>0)
			{
				$id=$this->id;
			}
			else
			{
				return false;
			}
		}
		
		if (!$this->exist())
		{
			return false;
		}
		if (trim($this->title)=="")
		{
			return false;
		}
		$query="UPDATE `lessons` SET `title`='$this->title', 
									`date`='$this->date', `articles`='$this->articles' WHERE `id`='".$id."'";
		if ($result=db::$db->query($query))
		{
			return true;
		}
		else
		{
			$this->error(2);
		}
	}
	
	public function exist($id=0)
	{
		if ($id<1)
		{
			if ($this->id>0)
			{
				$id=$this->id;
			}
			else
			{
				return false;
			}
		}
		$query="SELECT `id` FROM `lessons` WHERE `id`='$id' LIMIT 1";
		if ($result=db::$db->query($query))
		{
			if ($result->num_rows==1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			$this->error(2);
		}
	}
	public function returnit($str="")
	{
		$parse=new parser;
		$parse->additem("%id%",$this->id);
		$parse->additem("%title%",$this->title);
		$parse->additem("%date%",$this->date);
		$parse->additem("%articles%",$this->articles);
		return $parse->parse($str);
	}
}
?>